package service;

import model.RegionStats;
import org.apache.commons.csv.CSVFormat;
import org.apache.commons.csv.CSVRecord;
import org.springframework.beans.factory.InitializingBean;
import org.springframework.core.io.Resource;
import org.springframework.http.RequestEntity;
import org.springframework.http.ResponseEntity;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;
import org.springframework.web.client.RestTemplate;

import java.io.*;
import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Service
public class EpidemicDataService implements InitializingBean {
    /**
     * 初始化爬虫路径URL
     */
    private static final String URL="https://gitee.com/dgut-sai/COVID-19/raw/master/csse_covid_19_data/csse_covid_19_time_series/time_series_covid19_confirmed_global.csv";

    private  final List<RegionStats> confirmedCaseList=new ArrayList<>();

    public List<RegionStats> getRegionStatsList(){
        return confirmedCaseList;
    }

    /**
     * 爬取数据
     */
    @Scheduled(cron="${Scheduled.updateData}")
    public void confirmedCasesData() throws IOException {
        //爬取全球新型冠状病毒统计数据的csv文件
        RequestEntity<Void> requestEntity = RequestEntity
                .get(URI.create(URL))
                .headers(httpHeaders -> httpHeaders.add("User-Agent", "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/79.0.3945.79 Safari/537.36"))
                .build();
        ResponseEntity<Resource> exchange = new RestTemplate().exchange(requestEntity, Resource.class);
        Resource body = exchange.getBody();

        //通过Resource对象的getInputStream方法获取csv文件的输入流。
        InputStream inputStream = body.getInputStream();

        InputStreamReader reader = new InputStreamReader(inputStream);
        Reader in = new BufferedReader(reader);

        Iterable<CSVRecord> records = CSVFormat.RFC4180.withFirstRecordAsHeader().parse(in);
        for (CSVRecord record : records) {
            RegionStats regionStats = new RegionStats();
            regionStats.setState(record .get("Province/State"));
            regionStats.setCountry(record.get("Country/Region"));
            int case1=Integer.parseInt(record.get(record.size()-1));
            regionStats.setLatestTotalCases(case1);

            int case2=Integer.parseInt(record.get(record.size()-2));
            int case3=case1-case2;
            regionStats.setIncreaseCases(case3);
            confirmedCaseList.add(regionStats);
        }
    }

    @Override
    public void afterPropertiesSet() throws Exception {
        confirmedCasesData();
    }
}